<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
     *{
      margin: 0;
      padding: 0;
    }
    form{
      width: 400px;
      height: 180px;
      background-color: #f5f5f5;
      margin: auto;
      margin-top: 100px;
      padding: 0 50px;
      padding-top: 70px;
      text-align: center;
      
    }
    form>input{
      width: 310px;
      height: 38px;
      background-color: #fff;
      /* 取消激活框 */
      outline: none;
      border: 2px solid #a19d9d;
      box-sizing: border-box;
      text-indent: 10px;
      font-size: 13px;
      color: #cfc5c5;
      font-weight: bold;
    }
    form>button{
      margin-top: 10px;
      display: inline-block;
      width: 310px;
      height: 38px;
      border: 0;
      background-color: #4c7ab3;
      color:#f5f5f5;
      font-size: 16px;
      font-weight: 500;
    }
    form>p>a{
      text-decoration: none;
      font-size: 16px;
      margin-top: 20px;
      float: right;
      margin-left: 30px;
      color: #050505;
    }
  </style>
</head>
<body>
   <form action="" >
      <input type="text" name="username" placeholder="账号">
      <input type="password" name="password" id="" placeholder="密码">
      <button type="submit">登录</button>
      <p><a href="./02-register.html">去注册</a></p>
      <span></span>
   </form>
  
</body>
<script src="./axios.js"></script>
<script>
  let oUsername= document.querySelector('[type=text]')
  let oPassword= document.querySelector('[type=password]')
  let oForm=document.querySelector('form')
  let oSpan=document.querySelector('span')

  //绑定提交事件
  oForm.onsubmit=function(e){
    //1.阻止表单默认提交
    e.preventDefault()

    //2.拿取数据
    let username=oUsername.value
    let password=oPassword.value

    //3.数据非空效验(如果数据有一个为null,就提示 请输入全部信息 ,并终止程序)
    if(!username || !password){
      return alert('请输入全部信息')
    }
    //4.发送axios请求
    axios({ 
      url:'http://localhost:8888/users/login',
      method:'post',
      //将键值对数据转为name&zs的形式
      headers:{
        'content-type':'application/x-www-form-urlencoded'
      },
      data:{
        username,
        password
      }
    }).then(res=>{
      console.log(res)
      //如果登录失败,则提示 请重新登录
      if(res.data.code!=1){
       oSpan.innerText='亲,登录失败,请重新登录'
       oSpan.style.color='red'
        }

      //登录之后会生成一个token令牌,token用来判断用户是否登录.
      //登录之后,需要把token令牌和 id 存储到本地 (为什么需要存储? 首页需要查看你是否登录,token就是凭证)
      localStorage.setItem('token',res.data.token)
      localStorage.setItem('id',res.data.user.id)
      //跳转到登录
      location.href='04-index.html'
    })
  }
</script>
</html>